package com.chaos.auth.service.userdetails;

import cn.hutool.core.util.ObjectUtil;
import com.chaos.auth.api.data.TUserData;
import com.chaos.auth.api.dto.userdetails.UserUserDetails;
import com.chaos.auth.config.enums.AuthenticationIdentityEnums;
import com.chaos.auth.api.dto.RegisterDto;
import com.chaos.auth.service.TUserService;
import com.chaos.auth.service.auth.BaseUserDetailsService;
import com.chaos.auth.exception.PhoneNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Jacky
 */
@Slf4j
@Component("userInfoByPhoneDetailsService")
public class UserByPhoneDetailsService implements BaseUserDetailsService {

    @Resource
    private TUserService userService;

    @Override
    public UserDetails loadUserByPhone(String phone, Long tenantId) throws PhoneNotFoundException {
        TUserData queryData = TUserData.builder().phone(phone).build();
        queryData.setTenantId(tenantId);
        List<TUserData> userInfoDatas = userService.selectByData(queryData);
        TUserData userData = null;
        if (ObjectUtil.isEmpty(userInfoDatas)) {
            //userInfoData = (TUserData) register(registerDto);
        } else {
            userData = userInfoDatas.get(0);
        }
        UserUserDetails userDetails = new UserUserDetails(userData);
        if (!userDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        }
        userDetails.setAuthenticationIdentity(AuthenticationIdentityEnums.LogInIdentity.USER_PHONE.getCode());
        return userDetails;

    }


}
